package ar.edu.unlu.sistemas.ws.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class QueriesLogProcessor {
	
	public static final String UMEX_RR = "umex_rr";
	public static final String UMEX_SORT = "umex_sort";
	public static final String GRULIC_RR = "grulic_rr";
	public static final String GRULIC_SORT = "grulic_sort";
	public static String current = GRULIC_SORT;
	
	public static void main(String[] args) throws IOException, ParseException {
		Matcher m;
		String line;
		Date d;
		String query;
		int nTerms;
		FileWriter writer = new FileWriter(new File("/home/pepo/Dropbox/Tesis/Resultados/queries_"+current+".csv"));
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
		List<Map<String,Long>> queries = new ArrayList<Map<String,Long>>();
		queries.add(new HashMap<String,Long>());
		queries.add(new HashMap<String,Long>());
		queries.add(new HashMap<String,Long>());
		BufferedReader br = new BufferedReader(new FileReader(new File("/home/pepo/Dropbox/Tesis/Logs_Prueba_Grande/logs_"+current.toUpperCase()+"/web-service.log")));
		Pattern p = Pattern.compile("(\\d+-\\d+-\\d+\\s\\d+:\\d+:\\d+,\\d+)\\s-\\sweb-service\\s-\\sINFO\\s-\\s(\\d+).*\"([\\w\\d\\s]+)\".*");
		while ((line = br.readLine())!=null) {
			m = p.matcher(line);
			if (m.matches()) {
				d = df.parse(m.group(1));
				query = m.group(3);
				nTerms = query.split(" ").length-1;
				if (!queries.get(nTerms).containsKey(query)) queries.get(nTerms).put(query, d.getTime());
				else queries.get(nTerms).put(query, d.getTime()-queries.get(nTerms).get(query));
			}
		}
		br.close();
		for (Map<String,Long> times : queries) {
			for (String key : times.keySet()) {
				System.out.println(key+","+times.get(key));
				writer.append(key);
				writer.append(",");
				writer.append(times.get(key).toString());
				writer.append('\n');
			}
		}
		writer.flush();
		writer.close();
	}

}